<script>
import _ from 'lodash'
import Draggable from 'vuedraggable'
import dict from '../../dictionary/setting-panel.js'
import { fieldChangedHandler } from '../mixins.js'

export default {
  components: {
    Draggable
  },
  props: {
    id: String,
    fullField: String,
    shortField: String,
    value: Array,
    max: {
      type: Number,
      default: Infinity
    },
    min: {
      type: Number,
      default: -Infinity
    },
    step: {
      type: Number,
      default: 1
    }
  },
  functional: true,
  render (h, context) {
    const { props } = context
    const clone = _.cloneDeep(props.value)
    return (
      <form-item label={ dict[props.fullField] }>
        <Draggable
          element="ul"
          class="zlst-list--space"
          list={ clone }
          options={{ group: 'input-number-list', ghostClass: 'ghost', handle: '.moveable' }}
          on-change = { () => fieldChangedHandler(props.id, clone, context) }
        >
          {
            clone.map((item, index) => {
              return (
                <li key={ index }>
                  <input-number
                    value={ item.span }
                    max={ props.max }
                    small={ props.small }
                    step={ props.step }
                    on-on-change={
                      val => {
                        clone[index].span = val
                        fieldChangedHandler(props.id, clone, context)
                      }
                    }
                  />
                  <i-button
                    type="primary"
                    shape="circle"
                    size="small"
                    icon="md-add"
                    on-click={
                      () => {
                        const itemClone = _.cloneDeep(clone[index])
                        clone.splice(index + 1, 0, itemClone)
                        fieldChangedHandler(props.id, clone, context)
                      }
                    }
                  />
                  <i-button
                    type="warning"
                    shape="circle"
                    size="small"
                    icon="md-remove"
                    on-click={
                      () => {
                        clone.splice(index, 1)
                        fieldChangedHandler(props.id, clone, context)
                      }
                    }
                  />
                  <i-button class="moveable" type="default" shape="circle" size="small" icon="md-move" />
                </li>
              )
            })
          }
        </Draggable>
      </form-item>
    )
  }
}
</script>
